/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.starmeep.classes;

import com.jcraft.jsch.JSchException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author marc
 */
public class StarMeep {

    private StarCluster starcluster=null;
    private String job_name="";
    private String ctl_name="";
    private String path_job="";
    private int sizenodes;

    public StarMeep(String job_name, StarCluster starcluster, int sizenodes) throws JSchException, IOException, InterruptedException {
        this.starcluster=starcluster;
        this.job_name = job_name;
        this.sizenodes=sizenodes;
        createMeepMasterDir();
        //moveCTLtoMaster(ctl_local);
        
    }


    private void createMeepMasterDir() throws JSchException, IOException{
        StarSSH ssh=new StarSSH(starcluster.getKey_path(),starcluster.KNOWN_HOSTS, StarSSH.USER_ROOT,starcluster.getHostmaster());
        this.path_job="/home/"+job_name;
        ssh.executeCommand("sudo mkdir "+this.path_job);
        ssh.closeConnection();
    }

    public void deleteMeepMasterDir(){
        StarSSH ssh;
        try {
            ssh = new StarSSH(starcluster.getKey_path(), starcluster.KNOWN_HOSTS, StarSSH.USER_ROOT, starcluster.getHostmaster());
            ssh.executeCommand("rm -rf "+this.path_job);
            ssh.closeConnection();
        } catch (Exception ex) {
            Logger.getLogger(StarMeep.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void uploadCTL(File file, String filename) {
        StarSSH ssh;
        
        try {
            ssh = new StarSSH(starcluster.getKey_path(), starcluster.KNOWN_HOSTS, StarSSH.USER_ROOT, starcluster.getHostmaster());
            //ssh.executeCommand("rm -rf "+this.path_job);
            ssh.sftpFile(file, filename, this.path_job);
            ssh.closeConnection();
        } catch (Exception ex) {
            Logger.getLogger(StarMeep.class.getName()).log(Level.SEVERE, null, ex);
        }
        this.ctl_name=filename;
    }
    public String runCTL(String params){
        String res="";
        String ctlpath=this.path_job+"/"+ctl_name;
        String outpath=this.path_job+"/"+job_name+".out";
        String command="qsub -V -b y -cwd mpirun -n "+sizenodes+" /usr/bin/meep-mpi "+params+" "+ctlpath+" > "+outpath;
        System.out.println(command);
        //res = StarCommand.runCommand(command);
        StarSSH ssh;
        try {

            ssh = new StarSSH(starcluster.getKey_path(), starcluster.KNOWN_HOSTS, StarSSH.USER_ROOT, starcluster.getHostmaster());
            res=ssh.executeCommand(command);
            ssh.closeConnection();
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            Logger.getLogger(StarMeep.class.getName()).log(Level.SEVERE, null, ex);
        }
        int idx=res.indexOf("job");
        idx=idx+4;
        int idx2=res.indexOf(" ", idx);
        res=res.substring(idx, idx2-1);
        System.out.print("exito");
        return res;
    }

    public String stopCTL(String id){
        String res="";
        String command="qdel "+id;
        //res = StarCommand.runCommand(command);
        StarSSH ssh;
        try {
            ssh = new StarSSH(starcluster.getKey_path(), starcluster.KNOWN_HOSTS, StarSSH.USER_ROOT, starcluster.getHostmaster());
            res=ssh.executeCommand(command);
            ssh.closeConnection();
        } catch (Exception ex) {
            Logger.getLogger(StarMeep.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return res;
    }
    public String customCommand(String custom){
        String res="";
        StarSSH ssh;
        try {
            ssh = new StarSSH(starcluster.getKey_path(), starcluster.KNOWN_HOSTS, StarSSH.USER_ROOT, starcluster.getHostmaster());
            res=ssh.executeCommand("cd /home/"+job_name);
            res=ssh.executeCommand(custom);
            ssh.closeConnection();
        } catch (Exception ex) {
            Logger.getLogger(StarMeep.class.getName()).log(Level.SEVERE, null, ex);
        }

        return res;
    }
    public ArrayList<Map> getFilenamesSize(){
        ArrayList<Map> res=new ArrayList<Map>();
        //res = StarCommand.runCommand(command);
        StarSSH ssh;
        try {
            ssh = new StarSSH(starcluster.getKey_path(), starcluster.KNOWN_HOSTS, StarSSH.USER_ROOT, starcluster.getHostmaster());
            String linenames=ssh.executeCommand("ls");
            String[] names=linenames.split("\n");
            for(String name:names){
                Map<String,String> keyvalue=new HashMap<String, String>();
                //put name
                keyvalue.put("nameFile", name);

                // put size
                String sizestr=ssh.executeCommand("du -h "+name);
                String size=sizestr.split(" ")[0];
                keyvalue.put("sizeFile", size);

                // put download link
                String downloadstr="http://"+this.starcluster.getHostmaster()+"/starmeep-files/home/"+this.job_name+"/"+name;
                String download="<a href='"+downloadstr+"'>"+name+"</a>";
                keyvalue.put("linkFile", download);

                // put tail
                String tail=ssh.executeCommand("tail -10 "+name);
                keyvalue.put("lineFiles", tail);
                res.add(keyvalue);
            }
            ssh.closeConnection();
        } catch (Exception ex) {
            Logger.getLogger(StarMeep.class.getName()).log(Level.SEVERE, null, ex);
        }

        return res;
    }
    public String qstat(String id){
        String res="";
        String command="qstat -j "+id;
        StarSSH ssh;
        try {
            ssh = new StarSSH(starcluster.getKey_path(), starcluster.KNOWN_HOSTS, StarSSH.USER_ROOT, starcluster.getHostmaster());
            res=ssh.executeCommand(command);
            ssh.closeConnection();
        } catch (Exception ex) {
            Logger.getLogger(StarMeep.class.getName()).log(Level.SEVERE, null, ex);
        }

        return res;
    }
    public static String qhost() throws IOException, InterruptedException{
        String res="";
        String command="qhost";
        res = StarCommand.runCommand(command);

        return res;
    }
    public static String showFiles(boolean withsize) throws IOException, InterruptedException{
        String res="";
        String command="du -sh *";
        if(!withsize)
            command="ls";
        res = StarCommand.runCommand(command);

        return res;
    }

    public ArrayList getFilesNames() throws IOException, InterruptedException{
        ArrayList al=new ArrayList();
        String names=showFiles(false);
        String[] arrtmp=names.split("\n");
        for(String str: arrtmp){
            al.add(str);
        }
        return al;
    }

    public void moveMasterFiletoLocal(String file) throws IOException, InterruptedException{
        String command="scp -r "+StarSSH.USER_ROOT+"@"+starcluster.getHostmaster()+":"+this.path_job+"/"+file+" .";
        StarCommand.runCommand(command);
    }
    

    /**
     * @return the job_name
     */
    public String getJob_name() {
        return job_name;
    }

    /**
     * @param job_name the job_name to set
     */
    public void setJob_name(String job_name) {
        this.job_name = job_name;
    }

    /**
     * @return the starcluster
     */
    public StarCluster getStarcluster() {
        return starcluster;
    }

    /**
     * @param starcluster the starcluster to set
     */
    public void setStarcluster(StarCluster starcluster) {
        this.starcluster = starcluster;
    }

    /**
     * @return the path_job
     */
    public String getPath_job() {
        return path_job;
    }

    /**
     * @param path_job the path_job to set
     */
    public void setPath_job(String path_job) {
        this.path_job = path_job;
    }

    /**
     * @return the sizenodes
     */
    public int getSizenodes() {
        return sizenodes;
    }

    /**
     * @param sizenodes the sizenodes to set
     */
    public void setSizenodes(int sizenodes) {
        this.sizenodes = sizenodes;
    }
}
